﻿using IntoCommon.Util;
using IntoMes.Configs;
using IntoMes.Global;
using IntoMes.Models;
using IntoMes.PLC;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;


namespace IntoMes.ViewModels
{
    public class ProductionQueryViewModel : BindableBase
    {
        public ObservableCollection<ProduceData> Production { get; set; } = new ObservableCollection<ProduceData>();
        public ObservableCollection<ProductIdentity> BeforeProduction { get; set; } = new ObservableCollection<ProductIdentity>();
        public SparePartsManageViewModel SparePartsManage => Locator.Instance.SparePartsManage;

        public Service service => Locator.Instance.Service;
        public ProductionQueryViewModel()
        {
            //List = new ObservableCollection<ProductModel>(GlobalFunc.LoadXmlFile<List<ProductModel>>(Paths.recipeCfgFile));
            List = new List<ProductModel>();
            var lists = GlobalFunc.LoadXmlFile<List<string>>(Paths.recipeCfgFile);
            //GetProductNum(true);
            for (int i = 0; i < lists.Count; i++)
            {
                List.Add(new ProductModel()
                {
                    ModelName = lists[i],
                    ModelValue = i + 1,

                });

            }
            //GlobalFunc.WriteXmlFile(Paths.recipeCfgFile, List);
        }

        private string qrCode;
        private DateTime from = DateTime.Now;
        private DateTime to = DateTime.Now;
        object _locker = new object();
        public string QrCode
        {
            get => qrCode; set => SetProperty(ref qrCode, value);
        }
        public DateTime From
        {
            get => from; set => SetProperty(ref from, value);
        }
        public DateTime To
        {
            get => to; set => SetProperty(ref to, value);
        }



        #region 属性 

        private List<ProductModel> _List;
        /// <summary>
        /// 属性
        /// </summary>
        public List<ProductModel> List
        {
            get { return _List; }
            set
            {
                _List = value;
                RaisePropertyChanged("List");
            }
        }
        #endregion 属性

        #region 属性 

        private ProductModel _CurModel;
        /// <summary>
        /// 属性
        /// </summary>
        public ProductModel CurModel
        {
            get { return _CurModel; }
            set
            {
                _CurModel = value;
                RaisePropertyChanged("CurModel");
            }
        }



        #endregion 属性

        #region  定义周，月，季度的数量

        
         private int dayNum;
        /// <summary>
        /// 当天生产数量（切换型号时候PLC过站数量清零，这里需要查询后加上之后的过站数量）
        /// </summary>
        public int DayNum
        {
            get => dayNum; set => SetProperty(ref dayNum, value);
        }


        private int weekNum;
        /// <summary>
        /// 周生产数量
        /// </summary>
        public int WeekNum
        {
            get => weekNum; set => SetProperty(ref weekNum, value);
        }
        private int lastWeekNum;
        /// <summary>
        /// 上周生产数量
        /// </summary>
        public int LastWeekNum
        {
            get => lastWeekNum; set => SetProperty(ref lastWeekNum, value);

        }



        private int month;
        /// <summary>
        /// 月生产数量
        /// </summary>
        public int Month
        {
            get => month; set => SetProperty(ref month, value);
        }

        private int quarter;
        /// <summary>
        /// 季度生产数量
        /// </summary>
        public int Quarter
        {
            get => quarter; set => SetProperty(ref quarter, value);
        }

        private int year;
        /// <summary>
        /// 年度生产数量
        /// </summary>
        public int Year
        {
            get => year; set => SetProperty(ref year, value);
        }


        private int weekPlanNum;
        /// <summary>
        /// 周计划生产数量
        /// </summary>
        public int WeekPlanNum
        {
            get => weekPlanNum; set => SetProperty(ref weekPlanNum, value);
        }

        private int monthPlan;
        /// <summary>
        /// 月计划生产数量
        /// </summary>
        public int MonthPlan
        {
            get => monthPlan; set => SetProperty(ref monthPlan, value);
        }


        private int yearPlan;
        /// <summary>
        /// 年计划生产数量
        /// </summary>
        public int YearPlan
        {
            get => yearPlan; set => SetProperty(ref yearPlan, value);
        }







        #endregion


        #region  定义周，月，季度的NG数量



        /// <summary>
        /// 周NG生产数量
        /// </summary>
        public int ngWeekNum;

        public int NGWeekNum
        {
            get => ngWeekNum; set => SetProperty(ref ngWeekNum, value);
        }

        /// <summary>
        /// 月NG生产数量
        /// </summary>
        public int ngMonth;

        public int NGMonth
        {
            get => ngMonth; set => SetProperty(ref ngMonth, value);
        }

        /// <summary>
        /// 年度NG生产数量
        /// </summary>
        public int ngYear;


        public int NGYear
        {
            get => ngYear; set => SetProperty(ref ngYear, value);
        }





        #endregion




        private void Reset()
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                Production.Clear();
            });
        }

        private void Query()
        {
            Task.Run(() =>
            {
                lock (_locker)
                {
                    try
                    {
                        using (ProductionQueryContext db = new ProductionQueryContext())
                        {
                            Application.Current.Dispatcher.Invoke(() =>
                            {
                                Production.Clear();
                                List<ProduceData> query;
                                if (!string.IsNullOrEmpty(QrCode))
                                {
                                    query = db.Production.Where(o => o.OP10PartCode1 == QrCode ||
                                                                     o.OP10PartCode2 == QrCode ||
                                                                     o.OP20PartCode1 == QrCode ||
                                                                     o.OP30PartCode1 == QrCode ||
                                                                     o.OP60Code == QrCode).ToList();
                                    if (query.Count > 0)
                                    {
                                        foreach (var msg in query)
                                        {
                                            Production.Add(msg);
                                        }
                                    }
                                    else
                                    {
                                        MessageBox.Show("未包含该产品码");
                                        return;
                                    }
                                }
                                else
                                {


                                    From = Convert.ToDateTime(From.ToString("D").ToString());
                                    To = To.Date.AddHours(23).AddMinutes(59).AddSeconds(59);





                                    query = db.Production.Where(o => o.DateTime >= From && o.DateTime <= To).ToList();


                                    if (CurModel != null)
                                    {
                                        query = query.Where(o => o.ProductMode == CurModel.ModelName).ToList();
                                    }
                                    foreach (var msg in query)
                                    {

                                        Production.Add(msg);
                                    }
                                }
                                db.SaveChanges();
                            });
                        }
                    }
                    catch { }
                }
            });
        }



        private void BeforeQuery()
        {
            Task.Run(() =>
            {
                lock (_locker)
                {
                    try
                    {
                        using (BeforeProductionQueryContext db = new BeforeProductionQueryContext())
                        {
                            Application.Current.Dispatcher.Invoke(() =>
                            {
                                BeforeProduction.Clear();
                                Production.Clear();
                                List<ProductIdentity> query;
                                if (!string.IsNullOrEmpty(QrCode))
                                {
                                    query = db.Products.Where(o => o.OP10PartCode1 == QrCode ||
                                                                     o.OP10PartCode2 == QrCode ||
                                                                     o.OP20PartCode1 == QrCode ||
                                                                     o.OP30PartCode1 == QrCode ||
                                                                     o.OP60PartCode1 == QrCode).ToList();
                                    if (query.Count > 0)
                                    {
                                        foreach (var msg in query)
                                        {
                                            BeforeProduction.Add(msg);
                                        }
                                    }
                                    else
                                    {
                                        MessageBox.Show("未包含该产品码");
                                        return;
                                    }
                                }
                                else
                                {


                                    From = Convert.ToDateTime(From.ToString("D").ToString());
                                    To = To.Date.AddHours(23).AddMinutes(59).AddSeconds(59);





                                    query = db.Products.Where(o => o.DateTime >= From && o.DateTime <= To).ToList();


                                    if (CurModel != null)
                                    {
                                        query = query.Where(o => o.ProductMode == CurModel.ModelName).ToList();
                                    }
                                    foreach (var msg in query)
                                    {

                                        BeforeProduction.Add(msg);
                                    }
                                }


                                db.SaveChanges();
                                foreach (var item in BeforeProduction)
                                {
                                    ProduceData da = new ProduceData();
                                    da.ProductMode = da.ProductMode;
                                    da.IsRepair = da.IsRepair;
                                    da.OP10PartCode1 = item.OP10PartCode1;
                                    da.OP10PartCode2 = item.OP10PartCode2;
                                    da.OP10PartCode3 = item.OP10PartCode3;
                                    da.OP10Torque1 = item.OP10LD1NJ;
                                    da.OP10Torque2 = item.OP10LD2NJ;
                                    da.OP10Angle1 = item.OP10LD1JD;
                                    da.OP10Angle2 = item.OP10LD2JD;
                                    da.OP10Result = item.OP10Result;
                                    da.OP20PartCode1 = item.OP20PartCode1;
                                    da.OP20PartCode2 = item.OP20PartCode2;
                                    da.OP20Image = item.OP20PicturePath;
                                    da.OP20Result = item.OP20Result;
                                    da.OP30PartCode1 = item.OP30PartCode1;
                                    da.OP30Result = item.OP30Result;

                                    da.OP50Voltage1 = item.OP50DL1;
                                    da.OP50Voltage2 = item.OP50DY2;
                                    da.OP50Current1 = item.OP50PL1;
                                    da.OP50Current2 = item.OP50DL2;
                                    da.OP50Frequency1 = item.OP50PL1;
                                    da.OP50Frequency2 = item.OP50PL2;
                                    da.OP50Duty1 = item.OP50ZKB1;
                                    da.OP50Duty2 = item.OP50ZKB2;
                                    da.OP50Presure = item.OP50XLZ;
                                    da.OP50Leakage = item.OP50YLZ;
                                    da.OP50Result = item.OP50Result;
                                    da.OP60Code = item.OP60PartCode1;
                                    da.OP60Result = item.OP60Result;
                                    da.GP12Result = item.GP12Result;
                                    da.GP12Image1 = item.GP12Picture;
                                    da.GP12Image2 = item.GP12Picture2;
                                    da.JZResult = item.JZResult;
                                    da.JZImage1 = item.JZPicture1;
                                    da.JZImage2 = item.JZPicture2;
                                    Production.Add(da);
                                }

    
                            });
                        }
                    }
                    catch { }
                }
            });
        }

        /// <summary>
        /// 获取本周，本月，本季度的生产数
        /// </summary>
        /// <param name="IsExclTheDay">是否剔除当天</param>
        /// <param name="type">1：周2：月3：季度</param>
        public void GetProductNum(bool IsExclTheDay, string ProModel)
        {
            Task.Run(() =>
            {
                lock (_locker)
                {
                    try
                    {


                        // 获取今天的日期
                        System.DateTime today = System.DateTime.Today;
                        // 计算本周的开始日期（周一）
                        //var startOfWeek = today.AddDays(-(int)today.DayOfWeek + (int)DayOfWeek.Monday);
                        int daysToMonday = (int)today.DayOfWeek == 0 ? 6 : (int)today.DayOfWeek - 1;

                        // 计算周一的日期
                        DateTime startOfWeek = today.AddDays(-daysToMonday);

                        using (ProductionQueryContext db = new ProductionQueryContext())
                        {
                            Application.Current.Dispatcher.Invoke(() =>
                            {




                                // 计算本周结束日期的前一天（即不含今天）
                                var endOfWeek = today.AddDays(-1).AddHours(23).AddMinutes(59).AddSeconds(59);
                                var WeekList = db.Production.Where(o => o.DateTime >= startOfWeek && o.DateTime < endOfWeek && o.Result == "OK" && o.ProductMode == ProModel).ToList();
                                //NG数量
                                var NGWeekList = db.Production.Where(o => o.DateTime >= startOfWeek && o.DateTime < endOfWeek && o.GP12Result == "NG" && o.ProductMode == ProModel).ToList();
                                NGWeekNum= NGWeekList.Count();
                                WeekNum = WeekList.Count();
                                var MondayNum = WeekList.Where(pd => pd.DateTime.Date == startOfWeek.Date).Count();
                                service.WeekListCount[0]=MondayNum;
                                var TondayNum = WeekList.Where(pd => pd.DateTime.Date == startOfWeek.AddDays(1).Date).Count();
                                service.WeekListCount[1]= TondayNum;
                                var WednesDayNum = WeekList.Where(pd => pd.DateTime.Date == startOfWeek.AddDays(2).Date).Count();
                                service.WeekListCount[2]= WednesDayNum;
                                var ThursdayNum = WeekList.Where(pd => pd.DateTime.Date == startOfWeek.AddDays(3).Date).Count();
                                service.WeekListCount[3]= ThursdayNum;
                                var FridayNum = WeekList.Where(pd => pd.DateTime.Date == startOfWeek.AddDays(4).Date).Count();
                                service.WeekListCount[4]= FridayNum;
                                var SaturdayNum = WeekList.Where(pd => pd.DateTime.Date == startOfWeek.AddDays(5).Date).Count();
                                service.WeekListCount[5]= SaturdayNum;
                                var SunDayNum = WeekList.Where(pd => pd.DateTime.Date == startOfWeek.AddDays(6).Date).Count();
                                service.WeekListCount[6]= SunDayNum;

                                //计算上周的数据
                                DateTime lastWeekStart = startOfWeek.AddDays(-7);
                                lastWeekNum = db.Production.Where(o => o.DateTime >= lastWeekStart && o.DateTime < startOfWeek && o.Result == "OK" && o.ProductMode == ProModel).ToList().Count();

                                // 获取当前日期和时间
                                System.DateTime now = System.DateTime.Now;

                                // 查询本月的数据，但不包含当天的数据
                                Month = db.Production.Where(i => i.DateTime.Year == now.Year
                                                            && i.DateTime.Month == now.Month
                                                            && i.DateTime.Day != now.Day && i.Result == "OK" && i.ProductMode == ProModel).Count();

                                // 查询本月NG的数据，但不包含当天的数据
                                NGMonth = db.Production.Where(i => i.DateTime.Year == now.Year
                                                            && i.DateTime.Month == now.Month
                                                            && i.DateTime.Day != now.Day && i.GP12Result == "NG" && i.ProductMode == ProModel).Count();




                                // 计算本季度的开始和结束日期
                                System.DateTime startOfQuarter = new System.DateTime(today.Year, (today.Month - 1) / 3 * 3 + 1, 1);
                                System.DateTime endOfQuarter = startOfQuarter.AddMonths(3).AddDays(-1).AddHours(23).AddMinutes(59).AddSeconds(59);
                                //当天的结束
                                System.DateTime endDay = today.AddHours(23).AddMinutes(59).AddSeconds(59);
                                // LINQ 查询：本季度数量，不包含当天
                                Quarter = db.Production
                                    .Where(x => x.DateTime >= startOfQuarter && x.DateTime <= endOfQuarter && x.Result == "OK" && x.ProductMode == ProModel).Where(i => i.DateTime.Year == now.Year && i.DateTime.Month == now.Month && i.DateTime.Day != now.Day).Count();


                                // LINQ 查询：本年度数量，不包含当天

                                Year = db.Production
                                   .Where(x => x.DateTime.Year == now.Year && x.Result == "OK" && x.ProductMode == ProModel).Where(i => i.DateTime.Month == now.Month && i.DateTime.Day != now.Day).Count();
                                // LINQ 查询：本年度NG数量，不包含当天
                                NGYear = db.Production
                                  .Where(x => x.DateTime.Year == now.Year && x.GP12Result == "NG" && x.ProductMode == ProModel).Where(i => i.DateTime.Month == now.Month && i.DateTime.Day != now.Day).Count();



                                //获取当天的生产数
                                if (SparePartsManage.IsChangeModel)
                                {
                                    DayNum = db.Production
                                       .Where(x => x.Result == "OK" && x.ProductMode == ProModel).Where(i => i.DateTime.Year == now.Year && i.DateTime.Month == now.Month && i.DateTime.Day == now.Day).Count();
                                }
                                else
                                {

                                    DayNum = 0;
                                }

                                db.SaveChanges();
                            });
                        }


                        using (IssProducePlanContext db = new IssProducePlanContext())
                        {
                            Application.Current.Dispatcher.Invoke(() =>
                            {
                                // 计算本周
                                //var endOfWeek = today.AddDays(-1);
                                    
                                WeekPlanNum = db.ProductionPlan.Where(o =>o.DateTime >= startOfWeek && o.DateTime <= today && o.ProductMode == ProModel).Sum(p=>p.PlanCount);
                                // 查询本月的数据
                                MonthPlan = db.ProductionPlan.Where(i => i.DateTime.Year == today.Year
                                                            && i.DateTime.Month == today.Month
                                                            && i.ProductMode == ProModel).Sum(p => p.PlanCount);
                                // 查询本年的数据
                                YearPlan = db.ProductionPlan.Where(i => i.DateTime.Year == today.Year
                                                            && i.ProductMode == ProModel).Sum(p => p.PlanCount);

                                SparePartsManage.ProductNum= db.ProductionPlan.Where(i => i.DateTime== today
                                                            && i.ProductMode == ProModel).Sum(p => p.PlanCount);

                            });
                        }
                            
                            
                    }
                    catch { }
                }
            });
        }



        /// <summary>
        /// 更新或者添加计划
        /// </summary>
        /// <param name="identity"></param>
        public int LogProductPlan(IssProducePlan p)
        {
            int result = -1;
            lock (_locker)
            {
                try
                {
                    using (IssProducePlanContext db = new IssProducePlanContext())
                    {
                        var mp = db.ProductionPlan.Where(x => x.ProductMode == p.ProductMode.Trim() && x.DateTime == p.DateTime && x.CurBc == p.CurBc.Trim()).FirstOrDefault();
                        if (mp == null)
                        {
                            mp = new IssProducePlan();
                        }
                        mp.DateTime = p.DateTime;
                        mp.ProductMode = p.ProductMode;
                        mp.PlanCount = p.PlanCount;
                        mp.CurBc = p.CurBc;
                        db.ProductionPlan.AddOrUpdate(mp);
                        result = db.SaveChanges();
                    }
                }
                catch (Exception e)
                {

                }
            }
            return result;
        }
        /// <summary>
        ///  更新或者添加故障时间
        /// </summary>
        /// <param name="model"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void AddOrUpdateStationStopTime(StationStopTime p)
        {
            int result = -1;
            lock (_locker)
            {
                try
                {
                    using (StationStopTimeContext db = new StationStopTimeContext())
                    {
                        var mp = db.StopTime.Where(x => x.ProductMode == p.ProductMode.Trim() && x.DateTime == p.DateTime && x.StationName == p.StationName.Trim()).FirstOrDefault();
                        if (mp == null)
                        {
                            mp = new StationStopTime();
                        }
                        mp.DateTime = p.DateTime;
                        mp.ProductMode = p.ProductMode;
                        mp.StopTime = p.StopTime;
                        mp.StationName = p.StationName;
                        db.StopTime.AddOrUpdate(mp);
                        result = db.SaveChanges();
                    }
                }
                catch (Exception e)
                {

                }
            }
          
        }





        /// <summary>
        /// 查询当天是否下发计划
        /// </summary>
        /// <param name="identity"></param>
        public int GetProductPlanCount(string ProductMode)
        {
            int result = 0;
            lock (_locker)
            {
                try
                {
                    DateTime date= System.DateTime.Today;
                    using (IssProducePlanContext db = new IssProducePlanContext())
                    {
                        result = db.ProductionPlan.Where(x => x.ProductMode == ProductMode.Trim() && x.DateTime == date).ToList().Count;
                       
                    }
                }
                catch (Exception e)
                {

                }
            }
            return result;
        }
        



        private void Export()
        {
        }

        private void Write()
        {

        }

     

        private DelegateCommand resetCmd;
        private DelegateCommand exportCmd;
        private DelegateCommand queryCmd;
        private DelegateCommand beforeQueryCmd;
        private DelegateCommand writeCmd;
        public DelegateCommand ResetCmd => resetCmd ?? (resetCmd = new DelegateCommand(Reset));
        public DelegateCommand ExportCmd => exportCmd ?? (exportCmd = new DelegateCommand(Export));
        public DelegateCommand QueryCmd => queryCmd ?? (queryCmd = new DelegateCommand(Query));

        public DelegateCommand BeforeQueryCmd => beforeQueryCmd ?? (beforeQueryCmd = new DelegateCommand(BeforeQuery));
        
        public DelegateCommand WriteCmd => writeCmd ?? (writeCmd = new DelegateCommand(Write));
    }
}
